package com.example.securingserver;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.userdetails.UserDetails;

import java.security.Key;

/**
 * @author caiwl
 * @date 2020/5/13 10:42
 */
public class JwtsUtil {
    private static Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    public static String compact(UserDetails userDetails) {
        return Jwts.builder().setSubject(JSON.toJSONString(userDetails)).signWith(key).compact();
    }

    public static UserDetails parse(String jws) {
        String subject = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jws).getBody().getSubject();
        return JSON.parseObject(subject, UserDetails.class);
    }
}
